package com.chuanjiabao.wisdom.ui.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.chuanjiabao.wisdom.MainActivity;
import com.chuanjiabao.wisdom.R;
import com.chuanjiabao.wisdom.bean.InputBean;
import com.chuanjiabao.wisdom.bean.UpdateHeadCallBackBean;
import com.chuanjiabao.wisdom.databinding.FragmentInputPersionSecondBinding;
import com.chuanjiabao.wisdom.listener.OnBHClickListener;
import com.chuanjiabao.wisdom.ui.ActivityStack;
import com.chuanjiabao.wisdom.ui.view.DialogGLC;
import com.chuanjiabao.wisdom.util.GlideUtil;
import com.chuanjiabao.wisdom.util.GsonUtil;
import com.chuanjiabao.wisdom.util.HTTPAPI;
import com.chuanjiabao.wisdom.util.ImageUtils;
import com.chuanjiabao.wisdom.util.LogUtil;
import com.chuanjiabao.wisdom.util.PermissionUtil;
import com.chuanjiabao.wisdom.util.SpUtils;
import com.chuanjiabao.wisdom.util.StringUtil;
import com.chuanjiabao.wisdom.util.TimeHelper;
import com.chuanjiabao.wisdom.util.TimeUtil;
import com.chuanjiabao.wisdom.util.ToastUtil;
import com.chuanjiabao.wisdom.util.dialog.PhotoDialog;
import com.chuanjiabao.wisdom.util.dialog.SelectSexDialog;
import com.lzy.okgo.callback.StringCallback;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import cn.carbs.android.gregorianlunarcalendar.library.data.ChineseCalendar;
import okhttp3.Call;
import okhttp3.Response;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

import static android.app.Activity.RESULT_OK;
import static com.chuanjiabao.wisdom.bean.Constants.LOGINPRESSION;
import static com.chuanjiabao.wisdom.bean.Constants.REQUEST_CODE_ACCURATE_BASIC;
import static com.chuanjiabao.wisdom.bean.Constants.REQUEST_CODE_LOCATION;

public class InputPersionSecondFragment extends BaseLazyFragment {

    FragmentInputPersionSecondBinding binding;

    Uri uri;
    String capath;
    List<File> files = new ArrayList<>();
    String sex = "",
            birthday = "",
            birthday_type = "",
            truename = "",
            province = "",
            city = "",
            district = "",
            address = "",
            avatar = "";
    InputBean inputBean;

    @Override
    public int setLayoutId() {
        return R.layout.fragment_input_persion_second;
    }

    @Override
    protected View inflaterView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(
                LayoutInflater.from(getActivity()),
                R.layout.fragment_input_persion_second,
                container,
                false
        );
        binding.setFragment(this);
        return binding.getRoot();
    }

    @Override
    protected void onVisible() {
        String name = binding.etModuleTrueName.getText().toString().trim();
        InputBean inputBean = new InputBean();
        if (!TextUtils.isEmpty(name)) {
            inputBean.setName(name);
        }

        String birthday = binding.tvModuleSelectDay.getText().toString().trim();
        if (!TextUtils.isEmpty(birthday)) {
            inputBean.setBirthday(birthday);
        }

        String sex = binding.tvModuleSelectSex.getText().toString().trim();
        if (!TextUtils.isEmpty(sex)) {
            inputBean.setSex(sex);
        }

        SpUtils.putBean("module_inputBean", inputBean);
    }

    @Override
    protected void lazyLoad() {
        try {
            inputBean = (InputBean) SpUtils.getBean("module_inputBean");
            binding.tvModuleSelectSex.setText(inputBean.getSex());
            binding.tvModuleSelectDay.setText(inputBean.getBirthday());
            binding.etModuleTrueName.setText(inputBean.getName());
            switch (inputBean.getSex()) {
                case "男":
                    sex = "1";
                    break;
                case "女":
                    sex = "2";
                    break;
                default:
            }
        } catch (Exception e) {
            LogUtil.e("缓存暂无输入信息");
        }

        binding.tvModuleOk.setOnClickListener(this);
        binding.ivModuleHead.setOnClickListener(this);
        binding.tvModuleSelectSex.setOnClickListener(this);
        binding.llModuleSelectDay.setOnClickListener(this);
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tvModuleSelectSex:
                SelectSexDialog dialog = new SelectSexDialog(getActivity());
                dialog.show();
                dialog.setOnBHClickListener(new OnBHClickListener() {
                    @Override
                    public void onConfirmClick() {
                        sex = "2";
                        LogUtil.e("选择女性");
                        binding.tvModuleSelectSex.setText("女");
                    }

                    @Override
                    public void onCloseClick() {
                        sex = "1";
                        LogUtil.e("选择男性");
                        binding.tvModuleSelectSex.setText("男");

                    }
                });
                break;
            case R.id.tvModuleOk:
                truename = binding.etModuleTrueName.getText().toString().trim();
                if (TextUtils.isEmpty(truename)) {
                    ToastUtil.showToast("请输入姓名");
                    return;
                }

                if (TextUtils.isEmpty(birthday)) {
                    ToastUtil.showToast("请选择生日");
                    return;
                }

                if (TextUtils.isEmpty(sex)) {
                    ToastUtil.showToast("请选择性别");
                    return;
                }

                city = binding.etModuleCity.getText().toString().trim();
                address = binding.etModuleAddress.getText().toString().trim();
                udpateUserInfo();
                break;
            case R.id.llModuleSelectDay:
                Calendar calendar = Calendar.getInstance();
                if (!TextUtils.isEmpty(birthday)
                        && Long.parseLong(birthday) > 0
                ) {
                    String dateStr = TimeHelper.getInstance()
                            .getFormatedDateTime(
                                    "yyyy-MM-dd",
                                    Long.parseLong(birthday)
                            );

                    try {
                        @SuppressLint("SimpleDateFormat")
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        Date date = sdf.parse(dateStr);
                        calendar.setTime(date);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }

                DialogGLC mDialog = new DialogGLC(
                        getActivity(),
                        !TextUtils.equals("2", birthday_type)
                );
                mDialog.show();
                if (TextUtils.equals("2", birthday_type)) {
                    mDialog.initCalendar(
                            new ChineseCalendar(true,
                                    calendar.get(Calendar.YEAR),
                                    calendar.get(Calendar.MONTH) + 1,
                                    calendar.get(Calendar.DAY_OF_MONTH)));
                } else {
                    mDialog.initCalendar(calendar);
                }
                mDialog.setOnDataSelectListener((yangData, yinData, index) -> {
                    switch (index) {
                        case 0:
                            birthday_type = "1";
                            birthday = TimeUtil.timeToStr(yangData);
                            binding.tvModuleSelectDay.setText(yangData + "(阳历)");
                            break;
                        case 1:
                            birthday_type = "2";
                            birthday = TimeUtil.timeToStr(yinData);
                            binding.tvModuleSelectDay.setText(yinData + "(阴历)");
                            break;
                        default:
                    }
                });
                break;
            case R.id.ivModuleHead:
                showPhotoDialog();
                break;
        }
    }

    /**
     * 修改/提交个人信息
     */
    public void udpateUserInfo() {
        HTTPAPI.getInstance().udpateUserInfo(sex, birthday, birthday_type,
                truename, province, city, district, address, avatar,
                new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        if (!StringUtil.isFail(s)) {
                            StringUtil.showFail(getActivity(), s);
                        } else {
                            startActivity(new Intent(getActivity(), MainActivity.class));
                            ActivityStack.getScreenManager().popAllActivityExceptOne(MainActivity.class);
                        }
                    }
                });
    }

    public void showPhotoDialog() {
        PhotoDialog dialog = new PhotoDialog(getActivity());
        dialog.show();
        dialog.setOnBHClickListener(new OnBHClickListener() {
            @Override
            public void onConfirmClick() {
                photoPoint();
            }

            @Override
            public void onCloseClick() {
                photoAlbum();
            }
        });
    }

    public void photoPoint() {
        if (PermissionUtil.cameraPermission(getActivity(), LOGINPRESSION)) {
            uri = ImageUtils.createImagePathUri(getActivity());
            LogUtil.e("图片存储地址：" + uri);
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            startActivityForResult(intent, REQUEST_CODE_ACCURATE_BASIC);
        }
    }

    public void photoAlbum() {
        if (PermissionUtil.cameraPermission(getActivity(), REQUEST_CODE_LOCATION)) {
            Intent intent = new Intent("android.intent.action.PICK");
            intent.setType("image/*");
            startActivityForResult(intent, 3);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case LOGINPRESSION:
                if (PermissionUtil.loginPermission(getActivity(), LOGINPRESSION)) {
                    photoPoint();
                } else {
                    ToastUtil.showToast("请允许相关权限");
                    return;
                }
                break;
            case REQUEST_CODE_LOCATION:
                if (PermissionUtil.loginPermission(getActivity(), REQUEST_CODE_LOCATION)) {
                    photoAlbum();
                } else {
                    ToastUtil.showToast("请允许相关权限");
                    return;
                }
                break;
            default:
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE_ACCURATE_BASIC) {
                capath = uri + "";
                if ((capath + "").contains("content")) {
                    capath = ImageUtils.getRealPathFromURI(getActivity(), uri);
                } else if (capath.contains("file:///")) {
                    capath = capath.substring(7);
                } else {
                    capath = data.getData().toString();
                }
                LogUtil.e("手机拍摄图片" + capath);
                lubanMethod(capath);
                GlideUtil.setCircleMethod(getActivity(), capath, binding.ivModuleHead);
            } else if (requestCode == 3) {
                if (data == null) {
                    return;
                }
                capath = ImageUtils.getInstance().getFilePathMethod(getActivity(), data.getData());
                LogUtil.e("手机相册图片" + capath);
                GlideUtil.setCircleMethod(getActivity(), capath, binding.ivModuleHead);
                lubanMethod(capath);
            }
        }
    }

    public void lubanMethod(String str) {
        Luban.with(getActivity()).
                load(new File(str)).
                setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                        files.clear();
                    }

                    @Override
                    public void onSuccess(File file) {
                        files.add(file);
                        updateHead(file);
                    }

                    @Override
                    public void onError(Throwable e) {
                        LogUtil.e("鲁班压缩出错");
                    }
                }).launch();
    }

    public void updateHead(File file) {
        HTTPAPI.getInstance().updateHead(file, new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                if (!StringUtil.isFail(s)) {
                    StringUtil.showFail(getActivity(), s);
                } else {
                    UpdateHeadCallBackBean bean = GsonUtil.GsonToBean(s, UpdateHeadCallBackBean.class);
                    avatar = bean.getMsg();
                    ToastUtil.showToast("上传成功");
                }
            }
        });
    }

}
